package com.hy.web;

import java.util.Collections;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.hy.domain.Service;

@Controller
public class HyfwController {

	@RequestMapping("hyfw")
	public String hyfw(Model model,
			@RequestParam(defaultValue = "1", required = false) int page) {
		long count = Service.countServices(); // 总数
		int length = 10; // 读取条数
		int pages = (int) (count % length > 0 ? count / length + 1 : count
				/ length); // 总页数
		// 大于总页数，或者页码小于0，重定向到第一页
		if (page > pages || page < 1) {
			return "redirect:/hyfw.html?page=1";
		}
		int up = page > 1 && page <= pages ? page - 1 : 1; // 上一页
		int next = page > 0 && page < pages ? page + 1 : 1; // 下一页
		int start = (int) (count - page * length); // 起始位置

		start = start < 0 ? 0 : start;
		length = start == 0 ? (int) count % length : length;
		List<Service> services = Service.findServiceEntries(start, length);
		Collections.reverse(services); // 降序排列

		model.addAttribute("services", services);
		model.addAttribute("pages", pages);
		model.addAttribute("up", up);
		model.addAttribute("next", next);
		model.addAttribute("page", page);
		return "hyfw";
	}

	@RequestMapping("hyfw_xq")
	public String hyfwXq(Model model,
			@RequestParam(defaultValue = "1", required = false) long id) {
		/*
		Service service = Service.findService(id);
		if (service == null) {
			return "redirect:404";
		}
		service.setHits(service.getHits() + 1);
		service.merge();
		model.addAttribute("service", service);
		return "hyfw_xq";
		*/
		return "redirect:/hyfw/view/" + id + ".html";
	}

}
